<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Login extends CI_Controller {

    public function __construct() {
        session_start();
        parent::__construct();
    }

    public function index() {

        $data['error'] = "";

        if (isset($_SESSION['username'])) {
            redirect('admin');
        }

        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', 'Usuario', 'required|required');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');

        $this->form_validation->set_message('required', '%s ' . 'requerido');

        if ($this->form_validation->run() !== false) {
            // then validation passed. Get from db
            $this->load->model('login_model');
            $res = $this
                    ->login_model
                    ->verify_user(
                    $this->input->post('username'), $this->input->post('password')
            );

            if ($res !== false) {
                $_SESSION['username'] = $this->input->post('username');
                $_SESSION['type'] = $res[0]->type;
                redirect('admin');
            } else {
                $data['error'] = "<p class=\"alert label\">" . $this->lang->line('form_invalid') . "</p>";
            }
        }
        $this->load->view('admin/header');
        $this->load->view('admin/login_view', $data);
        $this->load->view('admin/footer');
    }

}